package com.chengzzz.mysite.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chengzzz.mysite.entity.User;
import com.chengzzz.mysite.enums.ResultEnum;
import com.chengzzz.mysite.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.chengzzz.mysite.utils.JWTUtils.returnEmail;


@CrossOrigin
public class JWTInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求头中令牌
      //  response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8082");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
//        response.Headers.Add("Access-Control-Allow-Origin", "*");
//        response.Headers.Add("Access-Control-Allow-Headers", "*");
//        response.Headers.Add("Access-Control-Allow-Methods", "GET, POST");
        String token = request.getHeader("token");
        try {

            DecodedJWT heard =  JWTUtils.verify(token);//验证令牌
           // Subject subject = SecurityUtils.getSubject();
            //User userDB = (User) subject.getPrincipal();
            String email = returnEmail(heard.getPayload());
            logger.info("token中取出的用户邮箱:"+email);
           // logger.info("当前登录的用户邮箱:"+userDB.getEmail());
//            if (!userDB.getEmail().equals(email)){
//                logger.info("用户邮箱不一致");
//                logger.info("token中取出的用户邮箱:"+email);
//                logger.info("当前登录的用户邮箱:"+userDB.getEmail());
//                throw new Exception("Token不一致");
//
//               // return new Result(ResultEnum.ACCOUNT_ERROR.getCode(), "滚你妈的你在逗我？", null, false);
//            }
            //System.out.println(getEmailFromString(new String(base64.decode(heard.getPayload()), "UTF-8")));
//            System.out.println("d+"+d.getHeader());
//            Subject subject = SecurityUtils.getSubject();
//            User userDB = (User) subject.getPrincipal();
//            UsernamePasswordToken tokenShiro = new UsernamePasswordToken(userDB.getEmail(),userDB.getPassword());
//
//            subject.login(tokenShiro);
//            User userDB = (User) subject.getPrincipal();
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效token");
            map.put("code", ResultEnum.TOKENERROR.getCode());
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
            map.put("code", ResultEnum.TOKENERROR.getCode());
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致!");
            map.put("code", ResultEnum.TOKENERROR.getCode());
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
            map.put("msg","自己在干点什么真就没逼数？非得给你拷起来？");
            map.put("code", ResultEnum.TOKENERROR.getCode());
        }
        catch (Exception e){
            e.printStackTrace();
            map.put("msg","滚你妈的臭批，你他妈在逗我?"+e);
            map.put("code", ResultEnum.TOKENERROR.getCode());
        }
        map.put("state",false);//设置状态
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }


}
